package com.huilian.iotbox.admin.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.huilian.iotbox.admin.dao.StatsUserDao;
import com.huilian.iotbox.admin.service.StatsStoreService;
import com.huilian.iotbox.admin.service.StatsUserService;
import com.huilian.iotbox.data.common.ServerResponse;
import com.huilian.iotbox.data.dto.StatsAgencyDto;
import com.huilian.iotbox.data.dto.StatsUserDto;
import com.huilian.iotbox.data.enums.StatsTypeEnum;
import com.huilian.iotbox.data.po.StatsUser;
import com.huilian.iotbox.data.properties.ConfigProperties;
import com.huilian.iotbox.data.properties.FileProperties;
import com.huilian.iotbox.data.utils.DateTimeUtils;
import com.huilian.iotbox.data.vo.StatsAgencyVo;
import com.huilian.iotbox.data.vo.StatsUserVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.Font;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;

/**
 * @author 谢洛涛
 * @date 2021/4/22 10:58
 */
@Service
@Slf4j
public class StatsUserServiceImpl implements StatsUserService {
    private static final Integer TYPE_DAY = 1;
    private static final Integer TYPE_MONTH = 2;
    @Autowired
    private FileProperties fileProperties;
    @Autowired
    private StatsStoreService statsStoreService;
    @Resource
    private StatsUserDao statsUserDao;
    @Autowired
    private ConfigProperties configProperties;
    @Override
    public void StatsDayUserJob(String startTime, String endTime, String yesterday) {
        Integer statsType = StatsTypeEnum.statsUser.getCode();
        List<StatsUser> statsUserList = statsStoreService.statsDayUser(yesterday, statsType);
        for (StatsUser statsUser : statsUserList) {
            statsUser.setDateStr(yesterday);
            statsUser.setType(TYPE_DAY);
            statsUserDao.insert(statsUser);
        }
        statsType = StatsTypeEnum.onDeviceStatsUser.getCode();
        List<StatsUser> statsUserListByDevice = statsStoreService.statsDayUser(yesterday, statsType);
        for (StatsUser statsUser : statsUserListByDevice) {
            statsUser.setDateStr(yesterday);
            statsUser.setType(TYPE_DAY);
            statsUserDao.insert(statsUser);
        }
    }

    @Override
    public void statsMonthUserJob(String startDateStr,String endDateStr) {
        List<StatsUser> statsUserList = statsUserDao.statsMonthUserJob(startDateStr,endDateStr);
        String date = DateTimeUtils.getPreviousMonth();
        for (StatsUser statsUser : statsUserList) {
            statsUser.setDateStr(date);
            statsUser.setType(TYPE_MONTH);
            statsUserDao.insert(statsUser);
        }
    }

    @Override
    public PageInfo findList(StatsUserDto statsUserDto) {
        if (statsUserDto.getType().equals(1)) {
            statsUserDto.setStartDateStr(DateTimeUtils.formatByPattern(statsUserDto.getCreateTime(), "yyyy-MM-dd"));
            statsUserDto.setEndDateStr(DateTimeUtils.formatByPattern(statsUserDto.getUpdateTime(), "yyyy-MM-dd"));
        } else {
            statsUserDto.setStartDateStr(DateTimeUtils.formatByPattern(statsUserDto.getCreateTime(), "yyyy-MM"));
            statsUserDto.setEndDateStr(DateTimeUtils.formatByPattern(statsUserDto.getUpdateTime(), "yyyy-MM"));
        }
        PageHelper.startPage(statsUserDto.getPageNum(), statsUserDto.getPageSize(), "su.dateStr desc, su.turnover desc");
        List<StatsUserVo> statsUserVoList = statsUserDao.findList(statsUserDto);
        PageInfo pagResult = new PageInfo(statsUserVoList);
        return pagResult;
    }

    @Override
    public StatsUserVo findCountYesterday(StatsUser statsUser) {
        return statsUserDao.findCountYesterday(statsUser);
    }

    @Override
    public List<StatsUserVo> findUserTurnoverTop(StatsUserDto statsUserDto) {
        if (statsUserDto.getType().equals(1)) {
            statsUserDto.setStartDateStr(DateTimeUtils.getMonthFirstDay());
            statsUserDto.setEndDateStr(DateTimeUtils.getMonthLastDay());
        } else {
            statsUserDto.setStartDateStr(DateTimeUtils.getYearFirstDay());
            statsUserDto.setEndDateStr(DateTimeUtils.getYearLastDay());
        }
        List<StatsUserVo> statsUserVoList = statsUserDao.findUserTurnoverTop(statsUserDto);
        if(statsUserDto.getUserInfo().getId().compareTo(172)==0){
            //定义50倍
            BigDecimal num = new BigDecimal(50);
            statsUserVoList.forEach(item->{
                item.setTurnover(item.getTurnover().multiply(num));
            });
        }

        return statsUserVoList;
    }

    @Override
    public List<StatsUserVo> findUserOrderCountTop(StatsUserDto statsUserDto) {
        if (statsUserDto.getType().equals(1)) {
            statsUserDto.setStartDateStr(DateTimeUtils.getMonthFirstDay());
            statsUserDto.setEndDateStr(DateTimeUtils.getMonthLastDay());
        } else {
            statsUserDto.setStartDateStr(DateTimeUtils.getYearFirstDay());
            statsUserDto.setEndDateStr(DateTimeUtils.getYearLastDay());
        }
        List<StatsUserVo> list = statsUserDao.findUserOrderCountTop(statsUserDto);
        if(statsUserDto.getUserInfo().getId().compareTo(172)==0){
            list.forEach(item->{
                item.setOrderCount(item.getOrderCount() * 50);
            });
        }
        return list;
    }

    @Override
    public List<StatsAgencyVo> findMonthlyTurnover(StatsAgencyDto statsAgencyDto) {
        return statsUserDao.findMonthlyTurnover(statsAgencyDto);
    }

    @Override
    public ServerResponse exportStatsUserList(StatsUserDto statsUserDto) {
        if (statsUserDto.getType().equals(1)) {
            statsUserDto.setStartDateStr(DateTimeUtils.formatByPattern(statsUserDto.getCreateTime(), "yyyy-MM-dd"));
            statsUserDto.setEndDateStr(DateTimeUtils.formatByPattern(statsUserDto.getUpdateTime(), "yyyy-MM-dd"));
        } else {
            statsUserDto.setStartDateStr(DateTimeUtils.formatByPattern(statsUserDto.getCreateTime(), "yyyy-MM"));
            statsUserDto.setEndDateStr(DateTimeUtils.formatByPattern(statsUserDto.getUpdateTime(), "yyyy-MM"));
        }
        List<StatsUserVo> statsUserVoList = statsUserDao.findList(statsUserDto);
        if(StringUtils.isEmpty(statsUserVoList) || statsUserVoList.size() == 0){
            return ServerResponse.createByErrorMessage("没有数据，可以导出");
        }
        String[] headers = new String[]{"日期","合作伙伴", "运营商","营业额（元）", "扫码支付（元）","现金收入（元）","活动收入（元）","抖音核销（元）","美团核销（元）","预计结算金额（单位：元）未扣除节假日结算的万分之二结算手续费，实际到账请前往【结算查询】","订单笔数","线上订单笔数","线下订单笔数","消费会员（个）","新增会员（个）"};
        // 定义日期格式
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日HH时mm分ss秒");
        sdf.setTimeZone(TimeZone.getTimeZone("GMT+8")); // 设置时区为东八区
        // 格式化日期
        String formattedCreateTime = sdf.format(statsUserDto.getCreateTime());
        String formattedUpdateTime = sdf.format(statsUserDto.getUpdateTime());
        String sheetName = "运营商统计" + formattedCreateTime + "至" + formattedUpdateTime;
        // 创建了一个excel文件
        HSSFWorkbook wb = new HSSFWorkbook();
        HSSFSheet sheet = wb.createSheet(sheetName);
        sheet.setDefaultColumnWidth(10);
        sheet.setColumnWidth(0, 30 * 256);
        sheet.setColumnWidth(1, 30 * 256);
        sheet.setColumnWidth(2, 25 * 256);
        sheet.setColumnWidth(3, 25 * 256);
        sheet.setColumnWidth(8, 25 * 256);
//        sheet.createFreezePane(0, 4, 0, 4);
        //标题样式
        HSSFCellStyle titleStyle = wb.createCellStyle(); // 样式对象
        //设置标题字体格式
        Font font = wb.createFont();
        //设置字体样式
        //font.setFontHeightInPoints((short) 20);   //--->设置字体大小
        font.setFontName("Courier New");   //---》设置字体，是什么类型例如：宋体
        font.setItalic(true);     //--->设置是否是加粗
        titleStyle.setFont(font);     //--->将字体格式加入到style1中
        titleStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 水平
        titleStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); //垂直

        //内容样式
        HSSFCellStyle contextStyle = wb.createCellStyle(); // 样式对象
        //设置标题字体格式
        Font contextfont = wb.createFont();
        contextfont.setFontHeightInPoints((short) 13);   //--->设置字体大小
        //设置字体样式
        contextStyle.setFont(contextfont);     //--->将字体格式加入到style1中
        contextStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 水平
        contextStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); //垂直
        contextStyle.setWrapText(true);//设置自动换行

        //表格第一行
        HSSFRow row1 = sheet.createRow(0);   //--->创建一行
        row1.setHeightInPoints(20);
        HSSFCell cell1 = row1.createCell(0);   //--->创建一个单元格
        // cell1.setCellStyle(titleStyle);
        cell1.setCellValue("运营商统计");
        //表格第二行
        HSSFRow r2 = sheet.createRow(1);
        r2.setHeightInPoints(20);
        HSSFCell c2 = r2.createCell(0);
        c2.setCellValue("起始时间：[" + sdf.format(statsUserDto.getCreateTime()) + "]  " + "  终止时间：[" + sdf.format(statsUserDto.getUpdateTime()) + "]");

        //标题
        HSSFRow row2 = sheet.createRow(3);           //--->创建一行
        contextStyle.setFillForegroundColor(HSSFColor.LEMON_CHIFFON.index);// 设置背景色
        contextStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        contextStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN); //下边框
        contextStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);//左边框
        contextStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);//上边框
        contextStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);//右边框
        contextfont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);//粗体显示
        contextStyle.setFont(contextfont);
        for (int i = 0; i < headers.length; i++) {
            HSSFCell cell2 = row2.createCell(i);
            cell2.setCellValue(headers[i]);
            cell2.setCellStyle(contextStyle);
        }
        int index = 0;//记录额外创建的sheet数量
        int j = 0;
        // 循环每行
        for (int i = 4; i < statsUserVoList.size() + 4; i++) {
            if ((i) % 65500 == 0) {
                sheet = wb.createSheet("salesList" + index);
                index++;
            }
            // 创建行
            HSSFRow row = sheet.createRow((i) - (index * 65500));


            //日期
            HSSFCell contextCell0 = row.createCell(0);
            contextCell0.setCellValue(statsUserVoList.get(j).getDateStr());

            //合作伙伴
            HSSFCell contextCell1 = row.createCell(1);
            if (!StringUtils.isEmpty(statsUserVoList.get(j).getAgencyName())) {
                contextCell1.setCellValue(statsUserVoList.get(j).getAgencyName());
            } else {
                contextCell1.setCellValue("无");
            }

            //运营商
            String userName = "";
            HSSFCell contextCell2 = row.createCell(2);
            if (!StringUtils.isEmpty(statsUserVoList.get(j).getName())) {
                userName =statsUserVoList.get(j).getName() + ":";
                contextCell2.setCellValue(statsUserVoList.get(j).getName());
            } else {
                contextCell2.setCellValue("");
            }
            if(!StringUtils.isEmpty(statsUserVoList.get(j).getUserName())){
                contextCell2.setCellValue(userName + statsUserVoList.get(j).getUserName());
            }


            //营业额（元）
            HSSFCell contextCell4 = row.createCell(3);
            if(!StringUtils.isEmpty(statsUserVoList.get(j).getTurnover())){
                contextCell4.setCellValue(statsUserVoList.get(j).getTurnover().toString());
            }else{
                contextCell4.setCellValue("");
            }

            //扫码支付（元）
            HSSFCell contextCell5 = row.createCell(4);
            if (!StringUtils.isEmpty(statsUserVoList.get(j).getTurnoverOnLine())) {
                contextCell5.setCellValue(statsUserVoList.get(j).getTurnoverOnLine().toString());
            } else {
                contextCell5.setCellValue("");
            }

            //现金收入（元）
            HSSFCell contextCell6 = row.createCell(5);
            if (!StringUtils.isEmpty(statsUserVoList.get(j).getTurnoverOffline())) {
                contextCell6.setCellValue(statsUserVoList.get(j).getTurnoverOffline().toString());
            } else {
                contextCell6.setCellValue("");
            }

            //活动收入（元）
            HSSFCell contextCell7 = row.createCell(6);
            if (!StringUtils.isEmpty(statsUserVoList.get(j).getActivityTurnover())) {
                contextCell7.setCellValue(statsUserVoList.get(j).getActivityTurnover().toString());
            } else {
                contextCell7.setCellValue("");
            }

            //抖音核销（元）
            HSSFCell contextCell8 = row.createCell(7);
            if (!StringUtils.isEmpty(statsUserVoList.get(j).getTurnoverDouYin())) {
                contextCell8.setCellValue(statsUserVoList.get(j).getTurnoverDouYin().toString());
            } else {
                contextCell8.setCellValue("");
            }

            //美团核销（元）
            HSSFCell contextCell9 = row.createCell(8);
            if (!StringUtils.isEmpty(statsUserVoList.get(j).getTurnoverMeiTuan())) {
                contextCell9.setCellValue(statsUserVoList.get(j).getTurnoverMeiTuan().toString());
            } else {
                contextCell9.setCellValue("");
            }

            //结算金额（元）
            HSSFCell contextCell10 = row.createCell(9);
            if (!StringUtils.isEmpty(statsUserVoList.get(j).getSettlementMoney())) {
                contextCell10.setCellValue(statsUserVoList.get(j).getSettlementMoney().toString());
            } else {
                contextCell10.setCellValue("");
            }

            //订单笔数
            HSSFCell contextCell11 = row.createCell(10);
            if(!StringUtils.isEmpty(statsUserVoList.get(j).getOrderCount())){
                contextCell11.setCellValue(statsUserVoList.get(j).getOrderCount());
            }else{
                contextCell11.setCellValue("");
            }

            //线上订单笔数
            HSSFCell context1Cell12 = row.createCell(11);
            if(!StringUtils.isEmpty(statsUserVoList.get(j).getOrderCountOnLine())){
                context1Cell12.setCellValue(statsUserVoList.get(j).getOrderCountOnLine());
            }else{
                context1Cell12.setCellValue("");
            }

            //线上订单笔数
            HSSFCell conte1t1Cell13= row.createCell(12);
            if(!StringUtils.isEmpty(statsUserVoList.get(j).getOrderCountOffline())){
                conte1t1Cell13.setCellValue(statsUserVoList.get(j).getOrderCountOffline());
            }else{
                conte1t1Cell13.setCellValue("");
            }

            //消费会员（个）
            HSSFCell conte11t1Cell14 = row.createCell(13);
            if(!StringUtils.isEmpty(statsUserVoList.get(j).getMemberConsumeNum())){
                conte11t1Cell14.setCellValue(statsUserVoList.get(j).getMemberConsumeNum());
            }else{
                conte11t1Cell14.setCellValue("");
            }

            //消费会员（个）
            HSSFCell conte11t11Cell15 = row.createCell(14);
            if(!StringUtils.isEmpty(statsUserVoList.get(j).getMemberNewNum())){
                conte11t11Cell15.setCellValue(statsUserVoList.get(j).getMemberNewNum());
            }else{
                conte11t11Cell15.setCellValue("");
            }

            j++;
            if (j >= statsUserVoList.size()) {
                j = 0;
            }
        }
        // 保存文件
        FileOutputStream fileOut = null;
        String fileName = fileProperties.getSaveImgPath() + "/" + sheetName + ".xls";

        try {
            File f = new File(fileName);
            if (!f.exists()) {
                f.createNewFile();
            }
            // 文件保存的地址和名称
            log.info("------------------------------iot后台库存记录导出:" + fileName);
            fileOut = new FileOutputStream(fileName);
            wb.write(fileOut);

        } catch (IOException e) {
            // 处理文件操作可能发生的IO异常
            e.printStackTrace();
            return ServerResponse.createByErrorMessage("文件保存失败:" + e + fileProperties.getSaveImgPath());
        } catch (Exception e) {
            // 其他异常
            e.printStackTrace();
            return ServerResponse.createByErrorMessage("文件保存过程中发生了错误:" + e);

        } finally {
            // 关闭流
            if (fileOut != null) {
                try {
                    fileOut.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        Map<String, String> map = new HashMap<>();
        map.put("fileName", sheetName + ".xls");
        map.put("downloadUrl",configProperties.getAdminBackEndUrl() + "/api/fileExport/download/" +sheetName + ".xls");
        return ServerResponse.createBySuccess(map);
    }
}
